package nodes.command;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import parser.ParserException;
import model.Model;
import nodes.AbstractNode;
import nodes.CloseParensNode;
import nodes.ConstantNode;
import nodes.OpenParensNode;


/**
 * Runs a command if an expression is not 0, else run another command
 */
public class IfelseC extends AbstractCommand
{
    
    public AbstractNode evaluate (List<AbstractNode> myArguments, Model model)
    {
        if (myArguments.size() < Integer.parseInt(resources.getString("ifelse")))
        {
            throw ParserException.BAD_ARGUMENTS;
        }

        AbstractNode expr = myArguments.get(0);
        int exprResult = expr.evaluate().getValue();
        
        AbstractNode currentArgument = null;
        int argNumber = 2;
        
        while(!(myArguments.get(argNumber) instanceof CloseParensNode)){
            currentArgument = myArguments.get(argNumber);
            if(exprResult != 0)
            {
                currentArgument.evaluate();
            }
            argNumber++;
        }
        argNumber+=2;
        currentArgument = myArguments.get(argNumber);
        
        while(!(myArguments.get(argNumber) instanceof CloseParensNode))
        {
            currentArgument = myArguments.get(argNumber);
            if(exprResult == 0)
            {
               currentArgument.evaluate();
            } 
            argNumber++;
        }

        return new ConstantNode(exprResult);
    }
    
    @Override
    public List<AbstractNode> setUpCommand (Queue<AbstractNode> outputQueue,String name)
    {
        List<AbstractNode> arguments = new ArrayList<AbstractNode>();
        try
        {
            while (!(outputQueue.peek() instanceof OpenParensNode)){
                arguments.add(outputQueue.poll().buildTree(outputQueue));
            }
            arguments.add(outputQueue.poll()); //Add OpenParensNode

            while (!(outputQueue.peek() instanceof CloseParensNode)){
                arguments.add(outputQueue.poll().buildTree(outputQueue));
            }
            arguments.add(outputQueue.poll()); //Add CloseParensNode
            arguments.add(outputQueue.poll()); //Add OpenParensNode
            
            while (!(outputQueue.peek() instanceof CloseParensNode)){
                arguments.add(outputQueue.poll().buildTree(outputQueue));
            }
            arguments.add(outputQueue.poll()); //Add CloseParensNode           
        }
        catch (NullPointerException e)
        {
            throw ParserException.BAD_TOKEN;
        }

        return arguments;
    }    
}
